package net.xo68.destiny.manager.eventHandle;

import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.node.NodeRegistry;
import net.xo68.destiny.core.discovery.NodeDiscoveryClient;
import net.xo68.destiny.core.eventbus.MessageEvent;
import net.xo68.destiny.core.util.TimeUtils;
import net.xo68.destiny.manager.service.NodeHeartbeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 工作节点下线
 */
@Component
@Slf4j
public class NodeDownlineEventHandle implements EventHandler<MessageEvent> {

    @Autowired
    private NodeHeartbeatService nodeHeartbeatService;
    @Autowired
    private NodeDiscoveryClient nodeDiscoveryClient;

    @Override
    public void onEvent(MessageEvent messageEvent, long l, boolean b) throws Exception {
        if(messageEvent.getBody()!=null){
            if(messageEvent.getBody() instanceof NodeRegistry){
                NodeRegistry nodeRegistry=messageEvent.mesageBody(NodeRegistry.class);
                nodeRegistry.setLastTime(TimeUtils.nowDate());
                log.debug("downline node:{}",nodeRegistry);
                nodeDiscoveryClient.removeWorkNode(nodeRegistry);
                nodeHeartbeatService.delete(nodeRegistry.getNodeHost(),nodeRegistry.getNodeType().name());
            }else {
                log.error("事件消息体为空,event: {}",messageEvent);
            }
        }else {
            log.error("事件消息体为空");
        }
    }
}
